package cool.zhoujie.pageselect;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

import cool.zhoujie.pageselect.databinding.ListItemBinding;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {

    private List<Selector> mList;

    private MainViewModel mViewModel;

    ItemAdapter(List<Selector> list,MainViewModel viewModel) {
        mList = list;
        mViewModel = viewModel;
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ListItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.list_item, parent, false);
        return new ItemHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull final ItemHolder holder, final int position) {
        holder.mBinding.setSelector(mList.get(position));
        holder.mBinding.setViewmodel(mViewModel);

        int selected_number = mViewModel.selected_number;

        //item的数字值
        if (!mList.get(position).number.equals("...")) {
            int i = Integer.parseInt(mList.get(position).number);
            if (selected_number == i) {
                View view = holder.mBinding.getRoot();
                RelativeLayout relativeLayout = view.findViewById(R.id.layout_list_item);
                relativeLayout.setBackground(relativeLayout.getContext().getResources().getDrawable(R.drawable.bg_selected));
            }
        }

        holder.mBinding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    static class ItemHolder extends RecyclerView.ViewHolder {

        ListItemBinding mBinding;

        ItemHolder(@NonNull ListItemBinding binding) {
            super(binding.getRoot());
            this.mBinding = binding;
        }
    }
}
